import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
// 根据环境不同引入不同api地址
import { baseUrl, baseApi } from '@/config'
import { ApplicantCode, ApiRsskey } from '@/config/common'
// create an axios instance
const IS_PROD = ['production', 'prod'].includes(process.env.VUE_APP_ENV)
const service = axios.create({
  baseURL: baseUrl + baseApi, // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    config.headers['X-CMSP-ApplicantCode'] = ApplicantCode
    config.headers['X-CMSP-ApiRsskey'] = ApiRsskey
    config.headers['x-access-app'] = 'dingding'

    if (store.getters.ticket) {
      config.headers['dashboard-ticket'] = store.getters.ticket
    } else {
      // todo 暂时开启sit 测试功能
      if (!IS_PROD) {
        config.headers['dashboard-ticket'] =
          'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXRob2QiOiJsZjIxbWFkcy1zZXJ2aWNlIiwibmV3U2lnbiI6Im51bGxzaWduYXR1cmUiLCJuYW1lIjoi5ZC06ZKwIiwic2VydmljZUlkIjoiY3BpYy5jYWYuY29tcG9uLnRlY2giLCJleHAiOjM1MjU0MDI0OTUsImRlcGFydG1lbnQiOiLmgLvlhazlj7gvIiwiaWF0IjoxNjMxOTQ2NDk1LCJ1c2VyaWQiOiIyNzUyMTUyMTYxNzA2MzAwIiwidXNlcm5hbWUiOiIxOTAzMDgwNCJ9.mHslDx1m76Y3Pl08f81KTPmBkqqCppAmS1dNNDwTCCs'
        // 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXRob2QiOiJsZjIxbWFkcy1zZXJ2aWNlIiwibmV3U2lnbiI6Im51bGxzaWduYXR1cmUiLCJuYW1lIjoi5ZSQ5YmRIiwiYXZhdGFyIjoiaHR0cHM6Ly9zdGF0aWMtbGVnYWN5LmRpbmd0YWxrLmNvbS9tZWRpYS9sQURQRGdROXF5MGVJWkROQThETkFjQV80NDhfOTYwLmpwZyIsInNlcnZpY2VJZCI6ImNwaWMuY2FmLmNvbXBvbi50ZWNoIiwiZXhwIjozNTI4NjgyMDg1LCJkZXBhcnRtZW50Ijoi5oC75YWs5Y-4LyIsImlhdCI6MTYzNTIyNjA4NSwidXNlcmlkIjoiMTMxNjM4MjEwMTY5NjEyOSIsInVzZXJuYW1lIjoiY190YW5namlhbi0wMDkifQ.fMppFq4vK42ff2mMLnW80bmW1L0t6KlhVfdz3LkQbog'
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    if (res.status && res.status !== 200) {
      // 登录超时,重新登录
      if (res.status === 401) {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }
      return Promise.reject(res || 'error')
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
